<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/4/9
 * Time: 9:32
 */

namespace plugin\admin\app\logic\upload;


use app\common\lib\TencentCos;
use Intervention\Image\ImageManagerStatic as Image;
use JamesHeinrich\GetID3\GetID3;
use plugin\admin\app\exception\AdminException;
use plugin\admin\app\logic\BaseLogic;
use plugin\admin\app\model\Upload;
use support\Request;
use support\Response;

class UploadLogic extends BaseLogic
{
    /**
     * 只返回当前管理员数据
     * @var string
     */
    protected $dataLimit = 'personal';

    protected static $instance;

    public function __construct()
    {
        $this->model = new Upload();
    }

    public static function getInstance()
    {
        //        if(is_object(self::$instance)){
//            return self::$instance;
//        }

        return new self();
    }

    public function select(Request $request): Response
    {
        if($request->input('order')==false){
            $request->inputSet('order','desc');
        }

        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        if (!empty($where['ext']) && is_string($where['ext'])) {
            $where['ext'] = ['in', explode(',', $where['ext'])];
        }
        if (!empty($where['name']) && is_string($where['name'])) {
            $where['name'] = ['like', "%{$where['name']}%"];
        }
        $field = $field ?:'id';
        $order = $order ?:'desc';
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    /**
     * 添加附件
     * @param Request $request
     * @return Response
     * @throws Exception|Throwable
     */
    public function insert(Request $request): Response
    {
        $file = current($request->file());
        if (!$file || !$file->isValid()) {
            throw new AdminException(4020,'未找到文件');
        }
        $data = $this->base($request, '/upload/files/'.date('Ymd'));
        $upload = new Upload;
        $upload->admin_id = $request->curAdminId;
        $upload->name = $data['name'];
        [
            $upload->url,
            $upload->name,
            $_,
            $upload->file_size,
            $upload->mime_type,
            $upload->image_width,
            $upload->image_height,
            $upload->ext
        ] = array_values($data);
        $upload->category = $request->post('category');
        $upload->save();
        return $this->json(0, '上传成功', [
            'url' => $data['url'],
            'name' => $data['name'],
            'size' => $data['size'],
            'tts' => $data['tts'],
        ]);
    }

    public function Update(Request $request): Response
    {
        return parent::update($request);
    }

    /**
     *  上传头像
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function avatar(Request $request): Response
    {
        $file = current($request->file());
        if ($file && $file->isValid()) {
            $ext = strtolower($file->getUploadExtension());
            if (!in_array($ext, ['jpg', 'jpeg', 'gif', 'png'])) {
                throw new AdminException(4020,'仅支持 jpg jpeg gif png格式');
            }
            $image = Image::make($file);
            $width = $image->width();
            $height = $image->height();
            $size = min($width, $height);
            $relative_path = 'upload/avatar/' . date('Ym');
            $real_path = base_path() . "/plugin/admin/public/$relative_path";
            if (!is_dir($real_path)) {
                mkdir($real_path, 0777, true);
            }
            $name = bin2hex(pack('Nn',time(), random_int(1, 65535)));
            $ext = $file->getUploadExtension();

//            $image->crop($size, $size)->resize(300, 300);
//            $path = base_path() . "/plugin/admin/public/$relative_path/$name.lg.$ext";
//            $image->save($path);

            $image->crop($size, $size)->resize(120, 120);
            $path = base_path() . "/plugin/admin/public/$relative_path/$name.md.$ext";
            $image->save($path);

            $res = TencentCos::getInstance()->uploadLocalFile($path,'admin/avatar');
//            $image->resize(60, 60);
//            $path = base_path() . "/plugin/admin/public/$relative_path/$name.$ext";
//            $image->save($path);
//
//            $image->resize(30, 30);
//            $path = base_path() . "/plugin/admin/public/$relative_path/$name.sm.$ext";
//            $image->save($path);
            @unlink($path);
            return json([
                'code' => 0,
                'msg' => '上传成功',
                'data' => [
                    //'url' => "/app/admin/$relative_path/$name.md.$ext"
                    'url' => "https://".$res['Location']
                ]
            ]);
        }

        throw new AdminException(4020,'file not found');
    }

    public function image(Request $request): Response
    {
        $data = $this->base($request, '/upload/img/'.date('Ymd'));
        $realpath = $data['realpath'];
//        try {
//            $img = Image::make($realpath);
//            $max_height = 1170;
//            $max_width = 1170;
//            $width = $img->width();
//            $height = $img->height();
//            $ratio = 1;
//            if ($height > $max_height || $width > $max_width) {
//                $ratio = $width > $height ? $max_width / $width : $max_height / $height;
//            }
//            $img->resize($width*$ratio, $height*$ratio)->save($realpath);
//        } catch (\Exception $e) {
//            //unlink($realpath);
//            return json( [
//                'code'  => 500,
//                'msg'  => '处理图片发生错误'
//            ]);
//        }

        $upload = new Upload;
        $upload->admin_id = admin_id();
        $upload->name = $data['name'];
        [
            $upload->url,
            $upload->name,
            $_,
            $upload->file_size,
            $upload->mime_type,
            $upload->image_width,
            $upload->image_height,
            $upload->ext
        ] = array_values($data);
        $upload->save();

        return json( [
            'code'  => 0,
            'msg'  => '上传成功',
            'data' => [
                'url' => $data['url'],
                'name' => $data['name'],
                'size' => $data['size'],
            ]
        ]);
    }

    public function video(Request $request): Response
    {
        $data = $this->base($request, '/upload/video/'.date('Ymd'));
        $realpath = $data['realpath'];

        $upload = new Upload;
        $upload->admin_id = admin_id();
        $upload->name = $data['name'];
        [
            $upload->url,
            $upload->name,
            $_,
            $upload->file_size,
            $upload->mime_type,
            $upload->image_width,
            $upload->image_height,
            $upload->ext
        ] = array_values($data);
        $upload->save();

        return json( [
            'code'  => 0,
            'msg'  => '上传成功',
            'data' => [
                'url' => $data['url'],
                'name' => $data['name'],
                'size' => $data['size'],
                'tts' => $data['tts'],
            ]
        ]);
    }

    /**
     * 获取上传数据
     * @param Request $request
     * @param $relative_dir
     * @return array
     * @throws \Exception
     */
    protected function base(Request $request, $relative_dir): array
    {
        $relative_dir = ltrim($relative_dir, '/');
        $file = current($request->file());
        if (!$file || !$file->isValid()) {
            throw new AdminException(4020,'未找到上传文件');
        }

        $base_dir = base_path() . '/plugin/admin/public/';
        $full_dir = $base_dir . $relative_dir;
        if (!is_dir($full_dir)) {
            mkdir($full_dir, 0777, true);
        }

        $ext = $file->getUploadExtension() ?: null;
        $mime_type = $file->getUploadMimeType();
        $file_name = $file->getUploadName();
        $file_size = $file->getSize();

        if (!$ext && $file_name === 'blob') {
            [$___image, $ext] = explode('/', $mime_type);
            unset($___image);
        }

        $ext = strtolower($ext);
        $ext_forbidden_map = ['php', 'php3', 'php5', 'css', 'js', 'html', 'htm', 'asp', 'jsp'];
        if (in_array($ext, $ext_forbidden_map)) {
            throw new AdminException(4020,'不支持该格式的文件上传');
        }

        $relative_path = $relative_dir . '/' . bin2hex(pack('Nn',time(), random_int(1, 65535))) . ".$ext";
        $full_path = $base_dir . $relative_path;
        $file->move($full_path);
        $image_with = $image_height = 0;
        if(in_array(strtolower($ext),['jpg','png','git','jpeg'])){
            if ($img_info = getimagesize($full_path)) {
                [$image_with, $image_height] = $img_info;
                $mime_type = $img_info['mime'];
            }
        }
        $voiceRe = [];
        if(in_array(strtolower($ext),['mp3','wav','aac','mp4','flv'])){
            $voiceRe= (new GetID3)->analyze($full_path);
        }

        $res = TencentCos::getInstance()->uploadLocalFile($full_path,$relative_dir);

        @unlink($full_path);
        return [
            'url'     => "https://".$res['Location'],
            'name'     => $file_name,
            'realpath' => "https://".$res['Location'],
            'size'     => $file_size,
            'mime_type' => $mime_type,
            'image_with' => $image_with,
            'image_height' => $image_height,
            'ext' => $ext,
            'tts' => $voiceRe['playtime_seconds']??'0',
        ];
    }
}